﻿#region

using System;
using KandaAlpha.Domain.Model.Entities;
using KandaAlpha.Domain.Repository;
using KandaAlpha.Infrastructure.Interfaces.Geocoding;
using KandaAlpha.Infrastructure.Interfaces.Messaging;
using KandaAlpha.Application.Interfaces;

#endregion

namespace KandaAlpha.Application.Impl
{
    public class RegistrationService : IRegistrationService
    {
        private readonly IAddressGeocoder addressGeocoder;
        private readonly IMessageSender messageSender;
        private readonly IUnitOfWorkFactory unitOfWorkFactory;
        private readonly IUserRepository userRepository;

        public RegistrationService(IAddressGeocoder addressGeocoder,
                                   IUserRepository userRepository,
                                   IMessageSender messageSender,
                                   IUnitOfWorkFactory unitOfWorkFactory)
        {
            this.addressGeocoder = addressGeocoder;
            this.userRepository = userRepository;
            this.messageSender = messageSender;
            this.unitOfWorkFactory = unitOfWorkFactory;
        }

        public bool RegisterUser(User user)
        {
            if (user == null)
            {
                throw new ArgumentNullException("user");
            }

            try
            {
                using (var uow = unitOfWorkFactory.Create())
                {
                    var coordinates = addressGeocoder.GetCoordinatesFrom(user.Address);

                    user.Coordinates = coordinates;

                    userRepository.Add(user);

                    uow.Commit();
                }
            }
            catch (Exception ex)
            {
                //TODO: do some logging here. 
                throw ex;
            }

            var isSent = messageSender.SendConfirmationMessage(user);

            return isSent;
        }
    }
}